import json,os
import fitz

def update_pdf_metadata(pdf_path, output_path, title, author, subject, creator, keywords, url):
    doc = fitz.open(pdf_path)
    for page in doc:
        page_width = page.rect.width
        page_height = page.rect.height
        footer_y = page_height - 30  # 距离页面底部30个单位
        footer_x = 10  # 距离页面左侧10个单位
        text = "Visit ReadingSummary.com for more information about '%s'." % title
        font_size = 12
        footer_rect = fitz.Rect(footer_x, footer_y, footer_x + len(text)*6, footer_y - 20)
        page.insert_text(footer_rect.tl, text, fontsize=font_size, color=(0, 0, 0.5))
        link_dict = {
            "kind": fitz.LINK_URI,  # URI link kind
            "from": footer_rect,  # Source rectangle
            "uri": url  # Target URL
        }
        page.insert_link(link_dict)

    metadata = doc.metadata
    metadata['title'] = title
    metadata['author'] = author
    metadata['subject'] = subject
    metadata['creator'] = creator
    metadata['keywords'] = keywords
    doc.set_metadata(metadata)
    doc.save(output_path, garbage=4, deflate=True, clean=True)
    doc.close()

def run(name):
    check = {}
    for line in os.popen("cat popular.txt rest.txt latest.txt").read().strip().split("\n"):
        if '\t' not in line: continue
        num, title = line.split("\t")
        check[num.strip()] = title.replace("/","|").strip().replace(" ","_")
    for line in open(name,"r"):
        num,title = line.strip().split("\t")
        num = int(num)
        fname = title.replace("/","|").replace(" ","_")
        if os.path.exists("output_%d.txt"%(num)) == False or os.path.exists("output_%d.pdf"%(num)) == False: continue
        if os.path.exists("../static/pdf/%s.pdf"%(fname)) == True: continue
        name = ''
        title = ''
        tag = ''
        for i,item in enumerate(open("output_%d.txt"%(num),"r")):
            if i == 0:
                if item.count(", ") == 2:
                    n1,n2,p1 = item.split(", ")
                    name = n1+" "+n2
                else: name = item.split(", ")[0]
            elif i == 1: title = item.strip()
            elif i > 2: tag = item.replace("|",', ')
        odata = json.loads(open("output_%d.json"%(num)).read().strip())
        topic = ','.join(odata['Genres'])
        keywords = ','.join(odata['Tags'])
        input_pdf_path = "output_%d.pdf"%(num)
        output_pdf_path = "../static/pdf/%s.pdf"%(fname)
        print(num,title,name,topic,keywords)
        update_pdf_metadata(
            input_pdf_path,
            output_pdf_path,
            title=title,
            author=name,
            subject=topic,
            creator='ReadingSummary.com',
            keywords=keywords,
            url='https://www.readingsummary.com/book/%s'%(check[str(num)])
        )

def generate_alpha(cate):
    result = {'a':[],'f':[],'k':[],'p':[],'u':[]}
    for line in open('./'+cate+'.txt',"r"):
        num,title = line.strip().split("\t")
        if title.lower()[0] in ['a','b','c','d','e']: result['a'].append(line.strip())
        elif title.lower()[0] in ['f','g','h','i','j']: result['f'].append(line.strip())
        elif title.lower()[0] in ['k','l','m','n','o']: result['k'].append(line.strip())
        elif title.lower()[0] in ['p','q','r','s','t']: result['p'].append(line.strip())
        else: result['u'].append(line.strip())
    return result

if __name__ == "__main__":
    # generate alphabet
    results = {'a':[],'f':[],'k':[],'p':[],'u':[]}
    result = generate_alpha('popular')
    for k in result: results[k] = results[k] + result[k]
    result = generate_alpha('latest')
    for k in result: results[k] = results[k] + result[k]
    result = generate_alpha('rest')
    for k in result: results[k] = results[k] + result[k]
    for k in results:
        with open("./alpha-"+k+'.txt',"w") as f: f.write("\n".join(results[k]))
    # update_pdf
    run('popular.txt')
    run('latest.txt')
    run('rest.txt')
